package com.ml.rabbitmq.a_simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author xr-8
 * @create 2021-04-14 22:56
 */
public class Consumer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        //1创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
//        connectionFactory.setVirtualHost("/ ");
        Connection connection = null;
        Channel channel = null;
        try {
            //2创建连接Connection
            connection = connectionFactory.newConnection("生产者");
            //3通过连接获取通道Channel
            channel = connection.createChannel();
            //4通过通道创建交换机，声明队列，绑定关系，路由Key,发送消息，和接收消息
            /**
             * 消费者消费消息
             * 1.消费哪个队列
             * 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
             * 3.消费的消息
             * 4.消费者未成功消费的回调
             */
            channel.basicConsume(QUEUE_NAME, true,
                    (consumerTag, delivery) -> System.out.println("收到消息是：" + new String(delivery.getBody(), "UTF-8")),
                    consumerTag -> System.out.println("接受失败了..."));

            System.out.println("开始接受消息!");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7关闭通道
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            //8关闭连接
            if (Objects.nonNull(connection) && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
